<?php
declare (strict_types = 1);
/**
 * 管理员
 */
namespace app\common\admin;

use think\facade\Db;
use app\common\facade\model\MaterialModel; // 引入素材类模型门面代理
use app\common\facade\model\ChannelInfoModel; // 引入频道模型门面
use app\common\facade\model\PgmListModel; // 引入编单门面
use app\common\facade\model\PgmListDetailModel; // 引入编单门面
use app\common\facade\model\AdvseqModel; // 引入广告时段模型
use app\common\facade\model\AdvPgmListModel; // 引入广告节目单表
use app\common\facade\model\AdvPgmListDetailModel; // 广告节目单详情表
use app\common\facade\model\PgmInfoDetailModel; // 节目库播出明细表
use app\common\facade\model\PgmListDetailTemplModel; // 模板节目明细表

class Editroom extends BaseAdmin
{
    public function pgmchannellist($param)
    {
        $channel_list = ChannelInfoModel::listsAll()->toArray();

        $where = [];
        if($param['day'] == 'depart') { //  只显示昨天以后的编单
            $beforeDay = date('Y-m-d', time() - 86400);
            $where[] = ['pgmlist_date', '>=', $beforeDay];
        }

        $pgmroom_list = PgmListModel::listsAll($where, [], 'pgmlist_date asc')->toArray();
        
        $data = [];
        if($channel_list) {
            foreach($channel_list as $k => $v) {
                $data[$k]['value'] = $v['id'];
                $data[$k]['label'] = $v['channel_name'];
            }

            foreach($pgmroom_list as &$c) {
                foreach($data as $d =>$f) {
                    if($c['channel_id'] == $f['value']) {
                        $data[$d]['children'][] = ['value' => $c['pgmlist_id'], 'label' => $c['pgmlist_date'], 'check_flag' => $c['check_flag']];
                    }
                }
            }
        }
        return $data;
    }

    // 审核编单
    public function pgmchannelCheck($param)
    {
        $where = [];

        if (isset($param['pl_id']) && !empty($param['pl_id'])) $where['pgmlist_id'] = $param['pl_id'];
        if (isset($param['word']) && !empty($param['word'])) $update['check_mind'] = $param['word'];
        if ($param['status'] == 1){
            $update['check_flag'] = 1;
        }elseif ($param['status'] == 2) {
            $update['check_flag'] = 0;
        }
        $update['check_time'] = date('Y-m-d H:i:s',time());

        $adminLoginInfo = $this->adminLoginInfo();
        $update['check_man']  = $adminLoginInfo['id'];

        $update= PgmListModel::where($where)->update($update);
        if ($update === false) exception('更新失败');
        return $update;
    }

    public function pgmchanneldel($ids)
    {
        // 当ids 不为空时
        if(!empty($ids)) {
            $res = PgmListModel::deleteData([['pgmlist_id', 'in', $ids]]);
            PgmListDetailModel::deleteData([['pgmlist_id', 'in', $ids]]);
        } else {
            return [
                'code' => 0,
                'msg'  => '参数未定义'
            ];
        }

        return [
            'code' => $res ? 1 : 0,
            'msg'  => $res ? '删除成功' : '删除失败'
        ];
    }

    public function pgmtemplDel($ids)
    {

        Db::startTrans();
        try {
            // 当ids 不为空时
            if(!empty($ids)) {
                $res = Db::table('t_pgm_list_templ')->where([['templ_id', 'in', $ids]])->delete();
                PgmListDetailTemplModel::deleteData([['templ_id', 'in', $ids]]);   
            } else {
                return [
                    'code' => 0,
                    'msg'  => '参数未定义'
                ];
            }
            Db::commit();
        } catch(\Exception $e) {
            Db::rollback();
            return $res = false;
        }

        return [
            'code' => $res ? 1 : 0,
            'msg'  => $res ? '删除成功' : '删除失败'
        ];
    }

    public function pgmchannelCreate($params)
    {
        if(isset($params['importType']) 
            && in_array($params['importType'], ['1', '2']) 
            && (!empty($params['fromdate']) || !empty($params['fromtempl']))) {
            return $this->pgmchannelCreateCopy($params); // 从原有编单 或模板复制
        } else {
            return $this->pgmchannelCreateDay($params); // 创建新的编单
        }
    }

    // 从原有模板 或原有日期复制创建编单明细
    public function pgmchannelCreateCopy($params)
    {
        $where = [];
        $where[] = ["pgmlist_date", '=', $params['start_date']];
        $where[] = ["channel_id", "=", $params['channel_id']];
        $count = PgmListModel::where($where)->count();

        // 1， 向t_pgm_list 插入一条当前日期编单记录。
        // 2,  向t_pgm_list_detail 加入节目时段记录（ps ：有效的节目时段，并统计时段下节目时长）
        $data = [];
        $adminLoginInfo = $this->adminLoginInfo();
        $data['pgmlist_date'] = $params['start_date'];
        $data['channel_id']   = $params['channel_id'];
        $data['creator'] = $adminLoginInfo['id'];
        $data['create_time'] = time();

        // 启动事务
        Db::startTrans();

        try {
            if($count > 0) { // 对原有编单重新创建
                $pgmlist_id = PgmListModel::where($where)->value('pgmlist_id');
                PgmListModel::deleteData([['pgmlist_id', '=', $pgmlist_id]]);
            }

            $nid = PgmListModel::insertGetId($data); // 获取编单主表主键

            if($params['importType'] == '1') { // 从日期下复制
                // 编单明细数据拷贝
                $pgmlistDetail = PgmListDetailModel::where([
                    ['pgmlist_id', '=', $params['fromdate']]
                ])->order('seq Asc')->select()->toArray();

                if($count > 0 && !empty($pgmlist_id)) { // 清除原来的编单明细记录
                    PgmListDetailModel::deleteData([['pgmlist_id', '=', $pgmlist_id]]);
                }
            } else if ($params['importType'] == '2') { // 从模板中导入
                $pgmlistDetail = PgmListDetailTemplModel::where([
                    ['templ_id', '=', $params['fromtempl']]
                ])->order('seq Asc')->select()->toArray();
            }
            
            foreach($pgmlistDetail as &$v) {                
                $v['pgmlist_id'] = intval($nid);
                
                if(isset($v['templ_id'])) {
                    unset($v['templ_id']);
                }                       
            }
            PgmListDetailModel::insertAll($pgmlistDetail);
            Db::commit();
            return $nid;
        } catch(\Exception $e) {
            Db::rollback();
            exception($e->getMessage(), $e->getCode());
        }
    }

    // 创建生成新的编单明细
    public function pgmchannelCreateDay($params)
    {
        $where = [];
        $where[] = ["pgmlist_date", '=', $params['start_date']];
        $where[] = ["channel_id", "=", $params['channel_id']];
        $count = PgmListModel::where($where)->count();

        // 1， 向t_pgm_list 插入一条当前日期编单记录。
        // 2,  向t_pgm_list_detail 加入节目时段记录（ps ：有效的节目时段，并统计时段下节目时长）
        $data = [];
        $adminLoginInfo = $this->adminLoginInfo();
        $data['pgmlist_date'] = $params['start_date'];
        $data['channel_id']   = $params['channel_id'];
        $data['creator'] = $adminLoginInfo['id'];
        $data['create_time'] = time();

        // 启动事务
        Db::startTrans();

        try {
            if($count > 0) { // 对原有编单重新创建
                $pgmlist_id = PgmListModel::where($where)->value('pgmlist_id');
                PgmListDetailModel::deleteData([['pgmlist_id', '=', $pgmlist_id]]);
                PgmListModel::deleteData([['pgmlist_id', '=', $pgmlist_id]]);
            }

            $nid = PgmListModel::insertGetId($data); // 获取编单主表主键
    
            // 广告节目单模型主键
            $pl_id = AdvPgmListModel::where([['play_date', '=', $params['start_date']], ['channel_id', '=', $params['channel_id']]])->value('pl_id');
    
            // 根据当前频道,和编单日期 获取当前日期时段列表。
            $adb_seq_list = AdvseqModel::advseqalive(['channel_id' => $params['channel_id'], 'play_date' => $params['start_date']]);
            // var_dump($adb_seq_list);
            $detail_data = []; // 节目编单数组；
            if(!empty($adb_seq_list['list'])) {
                $detail_data = array_merge($detail_data, self::createDetailData($adb_seq_list, $pl_id, $nid));  // 创建广告单编单明细
            }

            // 固定节目写入明细表
            PgmInfoDetailModel::addGuDingpgm(['channel_id' => $params['channel_id'], 'date' => $params['start_date']]);
            $pgmlib_detail_data = PgmInfoDetailModel::pgmInfoDayList(['channel_id' => $params['channel_id'], 'date' => $params['start_date']]); // 当日固定节目播出明细
            if(!empty($pgmlib_detail_data['list'])) {
                // var_dump($pgmlib_detail_data);
                $detail_data = array_merge($detail_data, self::createPgmPlanList($pgmlib_detail_data['list'], $nid)); // 创建节目库当天固定节目明细
            }
            
            $detail_data = self::detailPlayTimeCouputed($detail_data); // 播出时间重新排序
            PgmListDetailModel::insertAll($detail_data); // 写入到编单明细表
            // 提交事务
            // Db::rollback();
            Db::commit();
            return $nid;
        } catch(\Exception $e) {
            Db::rollback();
            exception($e->getMessage(), $e->getCode());
        }
    }

    // 创建生成广告单编单明细
    public function createDetailData($adb_seq_list, $pl_id, $nid)
    {
        $detail_data = [];
        if(!empty($adb_seq_list["list"])) {            
            foreach($adb_seq_list["list"] as $k => $v) {
                // 统计广告单时段下节目总时长。
                $pgm_len = AdvPgmListDetailModel::where([['advseg_id', '=', $v['adv_seq_id']], ['pl_id', '=', $pl_id]])->sum("pgm_len")?:0;

                $detail_data[$k]['pgmlist_id'] = $nid;                           
                $detail_data[$k]['s_time_code'] = $v['s_time_code'];
                $detail_data[$k]['grp_flag'] = 1;
                $detail_data[$k]['pgm_id'] = $v['adv_seq_id']; // 广告节目单时段ID
                $detail_data[$k]['pgm_name'] = $v['adv_seg_name'];
                $detail_data[$k]['ins_mode'] = ''; //属性
                $detail_data[$k]['switch_mode'] = ''; 
                $detail_data[$k]['pgm_seg'] = '';  // 时段 上午档， 中午档
                // 统计当前日期广告节目单时段下素材时长                
                $detail_data[$k]['pgm_len'] = intval($pgm_len?:0);
                $detail_data[$k]['pgm_type'] = 34; // 34代表广告类型 详情查找广告表
                $detail_data[$k]['sign_src'] = 0; // 信号源 默认为0 VDR类型；
                $detail_data[$k]['chain_id'] = ''; // 链路。 暂时不设
                $detail_data[$k]['line_router'] = ''; // 未知字段 不设
                $detail_data[$k]['mat_id'] = ''; // 素材ID                
                $detail_data[$k]['tape_markin'] = 0; // 磁带入点               
                $detail_data[$k]['tape_markout'] = $v['pgm_len_code'] - 1; // 磁带出点 
            }
        }
        return $detail_data;
    }

    // 节目库固定节目当日编单明细
    public function createPgmPlanList($list, $nid)
    {
        $data = [];
        foreach($list as $k => $v) {
            $data[$k]['pgmlist_id'] = $nid;                      
            $data[$k]['grp_flag'] = 0;
            $data[$k]['pgm_id'] = $v['pgm_id']; // 广告节目单时段ID
            $data[$k]['pgm_name'] = $v['pgm_name'];
            $data[$k]['ins_mode'] = ''; //属性
            $data[$k]['switch_mode'] = ''; 
            $data[$k]['pgm_seg'] = '';  // 时段 上午档， 中午档             
            $data[$k]['pgm_len'] = $v['pgm_len']?:0;
            $data[$k]['pgm_type'] = $v['pgm_type']; // 34代表广告类型 详情查找广告表
            $data[$k]['sign_src'] = 0; // 信号源 默认为0 VDR类型；
            $data[$k]['chain_id'] = ''; // 链路。 暂时不设
            $data[$k]['line_router'] = ''; // 未知字段 不设
            $data[$k]['mat_id'] = ''; // 素材ID                
            $data[$k]['tape_markin'] = 0; // 磁带入点               
            $data[$k]['tape_markout'] = $v['pgm_len'] - 1 < 0 ?: 0; // 磁带出点
            $data[$k]['s_time_code'] = $v['play_time'];
        }
        return $data;
    }

    public function detailPlayTimeCouputed($list) {
        $data = [];
        foreach($list as $k => $v) {
            if($k == 0) {
                $last_pgm_len = 0; 
                $last_stime = $v['s_time_code']; 
            }

            $data[$k] = $v;
            $data[$k]['seq'] = intval($k + 1);
            $data[$k]['play_mode'] = $k == 0 ? 0 : 1; // 将第一条播出设置为 定时
            $data[$k]['play_time'] = ($last_pgm_len == 0) ? $v['s_time_code'] : intval($last_stime + $last_pgm_len);                
            $data[$k]['s_time'] = ($last_pgm_len == 0) ? $v['s_time_code'] : intval($last_stime + $last_pgm_len);

            unset($data[$k]['s_time_code']);
            $last_pgm_len = $list[$k]['pgm_len'];  // 记录上一个节目时长
            $last_stime = $data[$k]['s_time']; // 记录上一个的开播时间
        }

        return $data;
    }

    // 总编室编单详情列表
    public function pgmdetaillist($param) 
    {
        if (!isset($param['type'])) exception('节目组参数异常!');

        $where = [];
        $where[] = ['pgmlist_id', '=', $param['type']]; 

        return PgmListDetailModel::detailLists($where);
    }

    public function pgmdetailAddEdit($params) 
    {
        if(!empty($params)) {
            // 启动事务
            Db::startTrans();
            $insert_data = [];
            $update_data = [];

            foreach($params as &$v) {
                $where = [];
                $where[] = ['pgmlist_id', '=', $v['pgmlist_id']];
                $where[] = ['seq', '=', $v['seq']];
                if(PgmListDetailModel::info($where)) {
                    $update_data[] = $v;
                    // PgmListDetailModel::addEditSave($v, $where);
                } else {
                    $insert_data[] = $v;
                    // PgmListDetailModel::create($v);
                }
            }

            try {
                if(!empty($insert_data)) {
                    PgmListDetailModel::insertAll($insert_data);
                }

                if(!empty($update_data)) {
                    foreach($update_data as &$x) {
                        $upwhere = [];
                        $upwhere[] = ['pgmlist_id', '=', $x['pgmlist_id']];
                        $upwhere[] = ['seq', '=', $x['seq']];
                        PgmListDetailModel::addEditSave($x, $upwhere);
                    }
                }
                // 提交事务
                Db::commit();
            } catch(\Exception $e) {
                Db::rollback();
                exception($e->getMessage(), $e->getCode());
            }
        }
        return true;
    }

    public function pgmdetailDel($ids)
    {
        $pgmlist_id = $ids[0]; 
        unset($ids[0]);
        $where = [];
        $where[] = ['pgmlist_id', '=', $pgmlist_id];
        if(!empty($ids)) {
            $where[] = ['seq', 'not in', $ids];
            PgmListDetailModel::deleteData($where);
        } else {
            PgmListDetailModel::deleteData($where);
        }

        return true;
    }

    // 节目模板列表
    public function pgmtemplList($channel_id)
    {
        $list = [];
        $where = ['channel_id' => $channel_id];
        if(!empty($where)) {
            $list = Db::table('t_pgm_list_templ')->where($where)->select();
        } else {
            exception('参数丢失！');
        }

        return $list;
    }

    public function pgmtemplAddEdit($param)
    {
        $where = [];
        $where[] = ['templ_id', '=', $param['templ_id']];
        $where[] = ['templ_name', '=', $param['templ_name']];
        $info = Db::table('t_pgm_list_templ')->where($where)->find();

        // 启动事务
        Db::startTrans();
        try {
            if(!empty($info)) { // 替换
                PgmListDetailTemplModel::deleteData([['templ_id', '=', $param['templ_id']]]);                
                $nid = $param['templ_id'];
            } else { // 新增
                $adminLoginInfo = $this->adminLoginInfo();
                $data = [];
                $data['templ_name'] = $param['templ_name'];
                $data['channel_id'] = $param['channel_id'];
                $data['creator'] = $adminLoginInfo['id'];
                $data['create_time'] = time();
                $nid = Db::table('t_pgm_list_templ')->insertGetId($data);
            }

            $pgmlistDetail = PgmListDetailModel::where([
                ['pgmlist_id', '=', $param['pgmlist_id']]
            ])->order('seq Asc')->select()->toArray();
    
            foreach($pgmlistDetail as &$v) {
                unset($v['play_time']);
                unset($v['pgmlist_id']);
                $v['templ_id'] = $nid;
            }
            PgmListDetailTemplModel::insertAll($pgmlistDetail);
            Db::commit();
            // Db::rollback();
        } catch(\Exception $e) {
            Db::rollback();
            exception($e->getMessage(), $e->getCode()); 
        }


        return true;
    }
}